import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/constant/constant.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../EcyRouter.dart';
import '../../constant/color_constant.dart';
import '../../ecycommon/EcyCommonWidgets.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../goods/model/EcyGoodsHomeIPListModel.dart';
import '../goods/model/EcyGoodsHomeIPModel.dart';

/// 注册后选择兴趣页面
class EcyRegisterAfterInterestSelectionPage extends EcyCommonBaseWidget {
  EcyRegisterAfterInterestSelectionPage();

  @override
  EcyRegisterAfterInterestSelectionPageState createState() {
    return EcyRegisterAfterInterestSelectionPageState(this);
  }
}

class EcyRegisterAfterInterestSelectionPageState
    extends EcyCommonBaseWidgetState with SingleTickerProviderStateMixin {
  late EcyCommonBaseWidget controller;

  EcyRegisterAfterInterestSelectionPageState(EcyCommonBaseWidget vc) {
    controller = vc;
  }

  int selectedCount = 0;
  List<EcyGoodsHomeIPModel> _ipList = [];
  bool loadingFlag = false;
  List<String> ipCodeList = [];
  late AnimationController _controller;
  final ScrollController _scrollController = ScrollController();
  int _total = 0;
  int _page = 1;

  @override
  void requestData() async {
    super.requestData();
    _refreshData(page: 1);
  }

  void _onScroll() {
    if (_page < _total) {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _refreshData(page: ++_page); // 加载更多数据的函数
      }
    }
  }

  Future<bool> _refreshData({int page = 1}) async {
    try {
      Map<String, dynamic> response = await EcyRequestbasemanager().post(
          "/app/api/app/commodityIp/list", {"size": "50", "current": page});
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        EcyGoodsHomeIPListModel ipListModel =
            EcyGoodsHomeIPListModel.fromJson(response["data"]);

        _total = ipListModel.pages;
        _page = ipListModel.current;
        if (ipListModel.records.isNotEmpty) {
          setState(() {
            _ipList.addAll(ipListModel.records);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取IP失败");
    }
    return true;
  }

  _loading() {
    setState(() {
      loadingFlag = true;
    });
  }

  void batchAddUserIp() async {
    if (loadingFlag) {
      return;
    }

    _loading();

    try {
      if (ipCodeList.isNotEmpty) {
        await EcyRequestbasemanager()
            .post("/app/userIp/batchAdd", {"ipCodeList": ipCodeList});
      }
    } catch (e) {
      EcyLogger.log(e.toString());
    } finally {
      setState(() {
        loadingFlag = false;
      });
      EcyRouter.pushNoParams(context, EcyRouter.registerSettingPage);
    }
  }

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat(); // 无限循环

    _scrollController.addListener(_onScroll);

    requestData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorConstant.White,
      appBar: PreferredSize(
          preferredSize: const Size.fromHeight(35),
          child: AppBar(
              backgroundColor: ColorConstant.White,
              scrolledUnderElevation: 0,
              actions: [
                GestureDetector(
                  onTap: () {
                    EcyRouter.pushNoParams(
                        context, EcyRouter.registerSettingPage);
                  },
                  child: const Text(
                    '跳过  ',
                    style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        letterSpacing: 1,
                        fontSize: 16,
                        color: Color.fromRGBO(0, 0, 0, 0.85)),
                  ),
                )
              ])),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            const Text('欢迎开启次元之旅',
                style: TextStyle(
                    fontFamily: "PingFang SC",
                    fontWeight: FontWeight.w700,
                    letterSpacing: 1,
                    fontSize: 18,
                    color: Color.fromRGBO(38, 38, 38, 1))),
            const SizedBox(height: 8),
            const Text('选择你近期感兴趣的内容',
                style: TextStyle(
                    fontFamily: "PingFang SC",
                    fontWeight: FontWeight.w400,
                    letterSpacing: 1,
                    fontSize: 14,
                    color: Color.fromRGBO(140, 140, 140, 1))),
            SizedBox(height: 20.h),
            Expanded(child: _buildInterestGrid()),
          ],
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        height: 60,
        elevation: 0,
        padding: EdgeInsets.zero,
        color: Colors.white,
        // shape: CircularNotchedRectangle(), // 底部导航栏打一个圆形的洞
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Expanded(
              flex: 1,
              child: Container(
                height: 52.0,
                padding: const EdgeInsets.only(
                    left: 16, top: 0, right: 16, bottom: 10),
                child: TextButton(
                  onPressed: () {
                    batchAddUserIp();
                  },
                  style: const ButtonStyle(
                    alignment: Alignment.center,
                    backgroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                    foregroundColor: WidgetStatePropertyAll(Colors.white),
                  ),
                  child: Stack(children: [
                    SizedBox(
                      height: 45.h,
                      width: 45.w,
                      child: Align(
                        alignment: Alignment.center,
                        child: Transform.translate(
                          offset: const Offset(-35.0, 0.0),
                          child: loadingFlag
                              ? Image.asset(
                                  width: 28.w,
                                  height: 25.h,
                                  alignment: Alignment.center,
                                  "assets/images/loading/loading.gif")
                              : null,
                        ),
                      ),
                    ),
                    Text('已选择${ipCodeList.length}个，下一步',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w500,
                            fontSize: 18.sp,
                            color: ColorConstant.White))
                  ]),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget avatar = Image.asset('assets/images/login_app_icon.png',
      width: 44, height: 44, fit: BoxFit.fitHeight);

  Widget _buildInterestGrid() {
    return GridView.builder(
        controller: _scrollController,
        itemCount: _ipList.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4, //横轴三个子widget
          childAspectRatio: 0.8,
          mainAxisSpacing: 16,
          crossAxisSpacing: 8, //宽高比为1时，子widget
        ),
        itemBuilder: (BuildContext context, int index) {
          return _buildInterestItem(_ipList[index]);
        });
  }

  Widget _buildInterestItem(EcyGoodsHomeIPModel item) {
    return GestureDetector(
        child: SizedBox(
          width: 80.w,
          height: 100.h,
          child: DecoratedBox(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8.0), //3像素圆角
                border: item.selected ?? false
                    ? Border.all(
                        color: const Color(0xFFEA4B9B),
                        width: 1,
                      )
                    : null,
              ),
              child: Padding(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 0.0, vertical: 16.0),
                  child: Stack(
                    alignment: AlignmentDirectional.topCenter,
                    children: [
                      CachedNetworkImage(
                        width: 45.w,
                        height: 45.w,
                        imageUrl: item.iconUrl ?? "",
                        imageBuilder: (context, imageProvider) => Container(
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8.r)),
                              image: DecorationImage(
                                  image: imageProvider, fit: BoxFit.cover)),
                        ),
                        placeholder: (context, url) => avatar,
                        errorWidget: (context, url, error) => avatar,
                      ),
                      Positioned(
                        top: 52.h,
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            item.name ?? "",
                            style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontWeight: FontWeight.w400,
                                fontSize: 12.sp,
                                color: const Color(0xFF262626),
                                overflow: TextOverflow.ellipsis),
                          ),
                        ),
                      ),
                    ],
                  ))),
        ),
        onTap: () {
          var ipCode = item.code ?? "";
          var selected = ipCodeList.contains(ipCode);
          if (!selected && ipCodeList.length >= 20) {
            EasyLoading.showToast("最多关注20个IP",
                toastPosition: EasyLoadingToastPosition.center,
                duration: const Duration(seconds: 2));
            return;
          }
          selected ? ipCodeList.remove(ipCode) : ipCodeList.add(ipCode);
          setState(() {
            item.selected = !(item.selected ?? false);
          });
        });
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
    _controller.dispose();
    _scrollController.dispose();
  }
}
